package socket.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TCP 服务端
 */
public class TCPServer {
    public ServerSocket serverSocket = null;
    //对serversocket 进行初始化
    //服务端的ServerSocket 需要指定端口号
    public TCPServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    //创建一个固定线程数的线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    public void start() throws IOException {
        //1.等待建立连接
        System.out.println("服务端已启动,等待客户端建立连接...");
        //没有客户端请求的话, accept会一直被阻塞, 直到有客户端来请求建立连接
        //clientSocket  就类似餐馆返回给用户的小票
        while (true){
            Socket clientSocket = serverSocket.accept();
            //2.接收数据并处理数据
            executorService.submit(()->{
                process(clientSocket);//此时, 服务端返回Socket, 服务端和客户端已经建立连接
            });

        }

    }

    private void process(Socket clientSocket) {
        System.out.printf("和客户端建立连接[%s:%d]\n",
                clientSocket.getInetAddress().getHostName(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream()){
            //方便起见, 使用Scanner
            Scanner scanner = new Scanner(inputStream);
            while (true){
                if (!scanner.hasNext()){
                    System.out.printf("和客户端断开连接[%s:%d]\n",
                            clientSocket.getInetAddress().getHostName(),clientSocket.getPort());
                    break;
                }
                String request = scanner.nextLine();
                System.out.printf("接收到客户端发送的数据[%s:%d]:%s\n",
                        clientSocket.getInetAddress().getHostName(),clientSocket.getPort(),request);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TCPServer server = new TCPServer(9090);
        server.start();
    }
}
